package com.example.smartcity_poverty.ui.AllService.ActivityManAge.activity

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Html
import android.view.MenuItem
import android.webkit.WebSettings
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_poverty.App
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.App.Companion.url
import com.example.smartcity_poverty.Base.BaseRecyclerAdapter
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.model.ActivityManAge.HListModel
import com.example.smartcity_poverty.logic.model.ActivityManAge.HListUserAll
import com.example.smartcity_poverty.logic.network.AppApi
import com.example.smartcity_poverty.logic.network.ServiceNET.Companion.create
import com.example.smartcity_poverty.logic.util.Util.glide
import com.example.smartcity_poverty.logic.util.Util.setUtils
import com.example.smartcity_poverty.logic.util.Util.show
import com.example.smartcity_poverty.ui.AllService.ActivityManAge.ManAgeViewModel
import com.example.smartcity_poverty.ui.AllService.ActivityManAge.adapter.ActManAgeListAdapter
import kotlinx.android.synthetic.main.activity_man_age_show_list.*
import kotlinx.android.synthetic.main.re_activity_manage_list_userall.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * 列表详情
 */
@Suppress("DEPRECATION")
class ManAgeShowListActivity : AppCompatActivity() {

    private val vm by lazy {
        ViewModelProviders.of(this)[ManAgeViewModel::class.java]
    }

    val id by lazy {
        intent.getStringExtra("id")?.toInt()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_man_age_show_list)
        title = "活动详情"


        id?.let {
            // 显示数据
            setIdShowList(id!!)
        }
    }

    // 活动列表展示
    private fun setIdShowList(id: Int) = coroutine(Dispatchers.Main) {
        create<AppApi>().getHListAll(id).apply {
            if (this.code == 200) {
                // 活动标题
                hShowTitle.text = this.data?.name
                // 活动照片
                glide(url + this.data?.imgUrl, hShowImage)
                // 显示活动内容
                hShowContent.setUtils(this.data?.content!!)


                /**
                 * 推荐活动列表
                 */

                vm.setHList(1)
                vm.hLiveData.observe(this@ManAgeShowListActivity, Observer { resources ->
                    resources.getOrNull()?.apply {
                        if (this.code == 200) {
                            vm.hListList.clear()
                            vm.hListList.addAll(this.rows!!)

                            // 填充数据
                            hSHowListRv.apply {
                                this.layoutManager = LinearLayoutManager(context)
                                this.adapter = ActManAgeListAdapter(
                                    vm.hListList,
                                    R.layout.re_activity_manage_list,
                                    3
                                )
                            }
                        }
                    }
                })

                /**
                 * 获取评论列表
                 */
                vm.setHListUserAll(id)
                vm.hListUserLiveData.observe(this@ManAgeShowListActivity, Observer { resources ->
                    resources.getOrNull()?.apply {
                        if (this.code == 200) {
                            vm.hListUserList.clear()
                            vm.hListUserList.addAll(this.rows!!)

                            // 填充数据
                            hList.apply {
                                this.layoutManager = LinearLayoutManager(context)
                                this.adapter = LikeName(
                                    vm.hListUserList,
                                    R.layout.re_activity_manage_list_userall
                                )
                                this.isNestedScrollingEnabled = true
                            }

                            // 发布评论
                            hListUserOk.setOnClickListener {
                                if (hListUserContent.text.toString().isEmpty()) {
                                    "不能为空".show()
                                } else {
                                    // 发表评论
                                    setComment(id)
                                }
                            }
                        } else "加载评论出错！".show()
                    }
                })
            } else "加载活动详情失败！".show()
        }
    }


    private fun setComment(id: Int) = coroutine(Dispatchers.Main) {
        create<AppApi>().setLikeName(getToken(), JSONObject().apply {
            put("activityId", id)
            put("content", hListUserContent.text.toString())
        }.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
            if (this.code == "200") {
                this.msg.show()
                runOnUiThread {
                    hList.adapter?.notifyItemChanged(vm.hListUserList.size)
                }
            } else this.msg.show()
        }
    }


    /**
     * 评论列表适配器
     */
    inner class LikeName(
        val list: MutableList<HListUserAll.RowsBean>,
        val layoutId: Int
    ) : BaseRecyclerAdapter<HListUserAll.RowsBean>(list, layoutId) {
        override fun setData(
            view: BaseViewHolder.ViewFind,
            data: HListUserAll.RowsBean,
            position: Int,
            holder: BaseViewHolder
        ) {
            val d = list[position]
            val v = holder.viewFind

            // 填充数据
            v.hUserName.text = d.userName
            v.hUserContent.text = d.content
        }

    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}